const express = require('express');
const router = express.Router();

const StudentActivity = require('../../models/SjoinActivity/SjoinActivity');// Assuming your model is here

// Endpoint to mark a student activity as attended and award points by studentId and activityId
router.put('/studentActivity/attend/:studentId/:activityId', async (req, res) => {
  try {
    const { studentId, activityId } = req.params; // 从 URL 参数获取 studentId 和 activityId
    const { points_awarded } = req.body; // 从请求体获取 points_awarded

    // Find the student activity record by studentId and activityId with status 'registered'
    const studentActivity = await StudentActivity.findOne({
      where: {
        student_id: studentId,
        activity_id: activityId,
        status: 'registered' // 只更新已报名的记录
      }
    });

    if (!studentActivity) {
      return res.status(404).json({
        success: false,
        message: '未找到匹配的学生活动记录或活动未报名'
      });
    }

    // Validate points_awarded
    // 根据实际的积分逻辑，这里可能需要调整或从其他地方获取积分值
    if (points_awarded === undefined || points_awarded < 0) {
         return res.status(400).json({
           success: false,
           message: '请提供有效的积分数值'
         });
    }

    // Update the record
    studentActivity.status = 'attended';
    studentActivity.attend_time = new Date(); // Set current timestamp
    studentActivity.points_awarded = points_awarded; // 设置积分

    await studentActivity.save();

    res.json({
      success: true,
      message: '学生活动状态更新成功',
      data: studentActivity
    });

  } catch (error) {
    console.error('更新学生活动状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新学生活动状态失败',
      error: error.message
    });
  }
});

// Endpoint to mark a student activity as missed by studentId and activityId
router.put('/studentActivity/missed/:studentId/:activityId', async (req, res) => {
  try {
    const { studentId, activityId } = req.params;

    // Find the student activity record by studentId and activityId with status 'registered'
    const studentActivity = await StudentActivity.findOne({
      where: {
        student_id: studentId,
        activity_id: activityId,
        status: 'registered' // 只更新已报名的记录
      }
    });

    if (!studentActivity) {
      return res.status(404).json({
        success: false,
        message: '未找到匹配的学生活动记录或活动未报名'
      });
    }

    // Update the record
    studentActivity.status = 'missed';
    await studentActivity.save();

    res.json({
      success: true,
      message: '学生活动状态已更新为未参加',
      data: studentActivity
    });

  } catch (error) {
    console.error('更新学生活动状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新学生活动状态失败',
      error: error.message
    });
  }
});

module.exports = router;
